package com.jiyun.controller;

import com.github.pagehelper.PageInfo;
import com.jiyun.mapper.RechargeMapper;
import com.jiyun.mapper.UserFriendMapper;

import com.jiyun.service.UserService;
import com.reading.pojo.*;
import com.reading.pojo.user.User;
import com.reading.pojo.user.UserFriend;
import com.reading.vo.Rmed;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.mysql.cj.conf.PropertyKey.logger;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@RestController
@RequestMapping("user")
@Slf4j

public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    //账号密码登录
    @RequestMapping("login1")
    public Rmed login1(String username, String password){
        List<User> user = userService.login(username,password);
        if (user.size()==0){
            return Rmed.error("账号或密码错误");
        }else {
//            user.get(0).setUserstatus(1);
//            user.get(0).setFriendId(user.get(0).getId());
            redisTemplate.boundValueOps("user"+user.get(0).getId()).set(user);
            userService.updatestatus(user.get(0).getId());
            user.get(0).setFriendId(user.get(0).getId());
            user.get(0).setUserstatus(1);
            redisTemplate.boundValueOps("user"+user.get(0).getId()).set(user);

            return Rmed.suceessData(user);
        }
    }

    //我的页面从redis中获取用户信息
    @RequestMapping("find")
    public Rmed find(Integer id){
//        long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号
//        System.out.println("手机号="+phone);
        List<User> user = (List<User>) redisTemplate.boundValueOps("user"+id).get();
        System.out.println("用户="+user);
        return Rmed.suceessData(user);
    }
    //退出登录
    @RequestMapping("logout")
    public void logout(Integer id ){
//        long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);
        List<User> user = (List<User>) redisTemplate.boundValueOps("user"+id).get();
        user.get(0).setUserstatus(0);
        redisTemplate.boundValueOps("user"+id).set(user);
    }
    //发送验证码
    @RequestMapping("sendcode")
    public Rmed sendcode(String phone){
        //判断手机号是否存在
        List<User> user = userService.findPhone(phone);
        if (user.size()!=0){
            return Rmed.suceessData(userService.sendcode(phone));
        }else {
            return Rmed.error("手机号不存在");
        }
    }
    //绑定新手机号的验证码发送
    @RequestMapping("sendcode1")
    public Rmed sendcode1(String phone){
        List<User> user = userService.findPhone(phone);
        if (user.size()!=0){
            return Rmed.error("手机号已存在");
        }else {
            return Rmed.suceessData(userService.sendcode(phone));
        }

    }
    //修改手机号
    @RequestMapping("updatephone")
    public Rmed updatePhone(String phone,String code,Integer id){
        String code1=(String) redisTemplate.boundValueOps("手机验证码"+phone).get();
        if (code1==null){
            return Rmed.error("验证码已过期");
        }else if (code1.equals(code)){
//            long phone1 = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);

            List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
            userFriendMapper.updatePhone(phone,user.get(0).getInvitation(),user.get(0).getUseremail(),user.get(0).getUserphone());
            user.get(0).setUserphone(phone);
            user.get(0).setUserstatus(1);
            redisTemplate.boundValueOps("user"+id).set(user);
            userService.updatePhone(user.get(0).getUserphone(),user.get(0).getId());

            return Rmed.suceessData(user);
        }else {
            return Rmed.error("验证码错误");
        }

    }
    //手机验证码登录
    @RequestMapping("login2")
    public Rmed login2(String phone,String code){
        String code1=(String) redisTemplate.boundValueOps("手机验证码"+phone).get();
        if (code1==null){
            return Rmed.error("验证码已过期");
        }else if (code1.equals(code)){
            List<User> user = userService.login2(phone);

            redisTemplate.boundValueOps("user"+user.get(0).getId()).set(user);
            userService.updatestatus(user.get(0).getId());
            user.get(0).setUserstatus(1);
            user.get(0).setFriendId(user.get(0).getId());
            redisTemplate.boundValueOps("user"+user.get(0).getId()).set(user);
            return Rmed.suceessData(user);
        }else {
            return Rmed.error("验证码错误");
        }
    }
    //邮箱验证码发送
    @RequestMapping("sendemail")
    public Rmed sendemail(String email){
        List<User> user = userService.findEmail(email);
        if (user.size()!=0){
            return Rmed.suceessData(userService.sendemail(email));
        }else {
            return Rmed.error("邮箱不存在");
        }
    }
    //邮箱登录
    @RequestMapping("login3")
    public Rmed login3(String email,String code){
        String code1=(String) redisTemplate.boundValueOps("邮箱验证码"+email).get();
        if (code1==null){
            return Rmed.error("验证码已过期");
        }else if (code1.equals(code)){
            List<User> user = userService.login3(email);
            Integer id=user.get(0).getId();
            redisTemplate.boundValueOps("user"+id).set(user);
            userService.updatestatus(user.get(0).getId());
            user.get(0).setUserstatus(1);
            user.get(0).setFriendId(user.get(0).getId());
            redisTemplate.boundValueOps("user"+id).set(user);
            return Rmed.suceessData(user);
        }else {
            return Rmed.error("验证码错误");
        }
    }
    //注册邮箱发送
    @RequestMapping("sendemail1")
    public Rmed sendemail1(String email){
        List<User> user = userService.findEmail(email);
        if (user.size()!=0){
            return Rmed.error("邮箱已存在");
        }else {
            return Rmed.suceessData(userService.sendemail(email));
        }

    }
    //注册
    @RequestMapping("add")
    public Rmed add(@RequestBody(required = false) User user){
        user.setUserstatus(0);
        user.setUsersex(1);
        user.setUserglod1(50);
        user.setUserglod1(0);
        user.setUserglod2(0);
        user.setBooks("");
        user.setIsvip(0);
        user.setHistory("");
        user.setUserimg("https://zhengfeixiang.oss-cn-beijing.aliyuncs.com/user/2024/11/29/05499ec4f34b41ebb0b3851cc38efec0.webp");
        String invitation = String.valueOf(generateRandomCode());
        System.out.println(invitation);
        user.setInvitation(invitation);
        userService.add(user);
        return Rmed.suceess();
    }
    //生成随机数的方法
    private static int generateRandomCode() {
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数
        return randomNumber;
    }
    //修改邮箱页面发送验证码
    @RequestMapping("sendemail2")
    public Rmed sendemail2(String email){
        List<User> user = userService.findEmail(email);
        if (user.size()!=0){
            return Rmed.error("邮箱已存在");
        }else {
            return Rmed.suceessData(userService.sendemail(email));
        }
    }
    //变更邮箱

    @RequestMapping("updateEmail")
    public Rmed updateemail(String email,String code,Integer id){
        String code1=(String) redisTemplate.boundValueOps("邮箱验证码"+email).get();
        if (code1==null){
            return Rmed.error("验证码已过期");
        }else if (code1.equals(code)){
//            long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);

            List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
            userFriendMapper.updateEmail(email,user.get(0).getInvitation(),user.get(0).getUseremail(),user.get(0).getUserphone());
            user.get(0).setUseremail(email);
            user.get(0).setUserstatus(1);
            redisTemplate.boundValueOps("user"+id).set(user);
            userService.updateEmail(user.get(0).getUseremail(),user.get(0).getId());

        }
        return Rmed.suceessData(user);
    }
    //修改昵称
    @RequestMapping("updateUsername")
    public Rmed updateUsername(String username,Integer id){
//        long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);

        List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
        user.get(0).setUsername(username);
        redisTemplate.boundValueOps("user"+id).set(user);
        userService.updateUsername(username,user.get(0).getId());
        userFriendMapper.updateusername(username,user.get(0).getInvitation(),user.get(0).getUseremail(),user.get(0).getUserphone());

        return Rmed.suceessData(user);
    }
    //修改性别
    @RequestMapping("updateSex")
    public Rmed updateSex(Integer sex,Integer id){
//        long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);

        List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
        user.get(0).setUsersex(sex);
        redisTemplate.boundValueOps("user"+id).set(user);
        userService.updateSex(sex,user.get(0).getId());
        userFriendMapper.updatesex(sex,user.get(0).getInvitation(),user.get(0).getUseremail(),user.get(0).getUserphone());

        return Rmed.suceessData(user);
    }

    //通过邀请码来添加朋友
    @Autowired
    UserFriendMapper userFriendMapper;
    @RequestMapping("/invitation")
    public Rmed invitation(String invitation,Integer id) {
        if (invitation == null || invitation.isEmpty()) {
            return Rmed.error("邀请码不能为空");
        }
        //根据朋友提供的邀请码查找到的朋友
        List<User> user = userService.findByInvitation(invitation);
        if (user.size() == 0) {
            return Rmed.error("邀请码不存在");
        } else {
            System.out.println("朋友信息"+user);
            //自己的信息
//            long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);
            List<User> user1 = (List<User>) redisTemplate.boundValueOps("user"+id).get();
            //判断朋友是否在数据库中,根据id,手机号或者id,邮箱来查询
            List<UserFriend> userFriend = userFriendMapper.findById(user1.get(0).getId(), user.get(0).getUseremail(), user.get(0).getUserphone());
            if (userFriend.size() == 0){//说明当前朋友没有添加过
                userFriendMapper.add(user1.get(0).getId(),user.get(0));
            }else {
                return Rmed.error("已经添加过该朋友");
            }
        }
        return Rmed.suceess();
    }
    //前端朋友页面显示
    @RequestMapping("findFriend")
    public Rmed findFriend(Integer id){

//            long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);
        List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
//            Integer id=user.get(0).getId();
        List<UserFriend> user1=userFriendMapper.findAll(id);
        return Rmed.suceessData(user1);


    }
    //查询所有用户信息
    @RequestMapping("findAll")
    public Rmed findAll(){
        List<User> user=userService.find();
        return Rmed.suceessData(user);
    }
    @RequestMapping("updateimg")
    public Rmed updateimg(String img,Integer id){
//        long phone = Long.parseLong(userphone.replace("\"", "")); // 去掉所有的双引号        System.out.println("手机号="+phone);
        List<User> user= (List<User>) redisTemplate.boundValueOps("user"+id).get();
        System.out.println("user="+user);
        if (user!=null){
            user.get(0).setUserimg(img);
            redisTemplate.boundValueOps("user"+id).set(user);
            userService.updateimg(img,user.get(0).getId());
            userFriendMapper.updateimg(img,user.get(0).getInvitation(),user.get(0).getUseremail(),user.get(0).getUserphone());
            return Rmed.suceess();
        }else {
            return Rmed.error("出错了，傻鸟，看你写的垃圾代码");
        }

    }

    @RequestMapping("addbooks")
    public Rmed addbooks(@RequestParam Integer pid, @RequestParam Integer uid) {
        // 参数验证
        if (pid == null || pid <= 0) {
            return Rmed.error("参数错误");
        }
        try {
            List<User> userList = (List<User>) redisTemplate.boundValueOps("user"+uid).get();
            System.out.println("获取="+userList);
            if (userList == null || userList.isEmpty()) {
                return Rmed.error("用户信息未找到");
            }

            User user = userList.get(0); // 考虑提供更灵活的用户选择方式
            Integer id = user.getId();

            User user1 = userService.findById(id);
            if (user1 == null) {
                return Rmed.error("用户信息未找到");
            }

            String books = user1.getBooks();
            String pidStr = String.valueOf(pid);

            if (books == null || books.isEmpty()) {
                books = pidStr;
            } else {
                // 处理空字符串情况
                if (",".equals(books)) {
                    books = pidStr;
                } else {
                    for (String book : books.split(",")) {
                        if (book.trim().equals(pidStr)) {
                            return Rmed.error("已经添加过该书籍");
                        }
                    }
                    books = books + "," + pidStr;
                }
            }

            user1.setBooks(books);
            userService.updatebooks(books, id); // 确保此方法正确更新书籍信息

            // 更新用户信息到Redis
            userList.get(0).setBooks(books); // 更新用户对象
            redisTemplate.boundValueOps("user"+uid).set(userList);
            System.out.println("更新="+userList.get(0));

            return Rmed.suceess();
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            return Rmed.error("系统错误，请稍后再试");
        }
    }

    @RequestMapping("/deleteBooks")
    public Rmed deleteBooks(@RequestParam String ids, @RequestParam Integer id) {
        // 输入验证
        if (id == null || ids == null) {
            return Rmed.error("无效的输入");
        }
        // 获取用户信息
        User user = userService.findUserById(id);
        if (user == null) {
            return Rmed.error("用户不存在");
        }
        // 获取用户的书籍信息
        String books = user.getBooks();
        if (books == null || books.isEmpty()) {
            return Rmed.error("用户没有书籍");
        }

        // 解析书籍ID字符串
        String[] bookIds = ids.split(",");
        String[] booksstr = books.split(",");

        // 使用集合操作移除相等的元素
        List<String> bookIdsList = Arrays.asList(bookIds);
        List<String> booksList = new ArrayList<>(Arrays.asList(booksstr));

        // 移除 booksList 中存在于 bookIdsList 中的元素
        booksList.removeAll(bookIdsList);

        // 将新的 books 字段存入 user 中
        String updatedBooks = String.join(",", booksList);
        user.setBooks(updatedBooks);
        System.out.println("updatedBooks=" + updatedBooks);
        userService.updatebooks(updatedBooks, id);
        // 更新用户信息到Redis
        List<User> userList = (List<User>) redisTemplate.boundValueOps("user"+id).get();
        System.out.println("userList1=" + userList.get(0));
        userList.get(0).setBooks(updatedBooks);
        redisTemplate.boundValueOps("user"+id).set(userList);
        System.out.println("userList=" + userList.get(0));
        return Rmed.suceess();
    }

    @RequestMapping("addhistory")
    public Rmed addhistory(@RequestParam Integer pid, @RequestParam Integer uid) {
        // 参数验证
        if (pid == null || pid <= 0) {
            return Rmed.error("参数错误");
        }
        try {
            List<User> userList = (List<User>) redisTemplate.boundValueOps("user"+uid).get();
            System.out.println("获取="+userList);
            if (userList == null || userList.isEmpty()) {
                return Rmed.error("用户信息未找到");
            }

            User user = userList.get(0); // 考虑提供更灵活的用户选择方式
            Integer id = user.getId();

            User user1 = userService.findById(id);
            if (user1 == null) {
                return Rmed.error("用户信息未找到");
            }

            String History = user1.getHistory();
            String pidStr = String.valueOf(pid);

            if (History == null || History.isEmpty()) {
                History = pidStr;
            } else {
                // 处理空字符串情况
                if (",".equals(History)) {
                    History = pidStr;
                } else {
                    for (String book : History.split(",")) {
                        if (book.trim().equals(pidStr)) {
                            return Rmed.error("已经添加过该书籍");
                        }
                    }
                    History = History + "," + pidStr;
                }
            }

            user1.setHistory(History);
            userService.updateHistory(History, id); // 确保此方法正确更新书籍信息

            // 更新用户信息到Redis
            userList.get(0).setHistory(History); // 更新用户对象
            redisTemplate.boundValueOps("user"+uid).set(userList);
            System.out.println("更新="+userList.get(0));

            return Rmed.suceess();
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            return Rmed.error("系统错误，请稍后再试");
        }
    }



    //web端
    @RequestMapping("finduser")
    public Rmed finduser(@RequestBody User user,Integer pageNo,Integer pageSize){
        PageInfo<User> pageInfo = userService.finduser(user,pageNo,pageSize);
        return Rmed.suceessData(pageInfo);
    }

    @RequestMapping("xz")
    public Rmed xz(Integer id,Integer userglod1){
        User byId = userService.findById(id);
        if (userglod1>byId.getUserglod1()){
            return Rmed.error("您的金币不足");
        }else {
            int a=byId.getUserglod1()-userglod1;
            return Rmed.suceessData(userService.xz(a,id));
        }

    }

    @RequestMapping("/updateUserGlod1")
    public void updateUserGlod1(@RequestBody OrderVo orderVo){
        userService.updateUserGlod1(orderVo);
    }

    @RequestMapping("/findOneUser")
    public User findOneUser(Integer id){
        return userService.findOneUser(id);
    }

    @RequestMapping("/updateUserGlod2")
    public void updateUserGlod2(@RequestBody GlodVO glodVO){
        userService.updateUserGlod2(glodVO);
    }

    @RequestMapping("/purchase")
    public Rmed purchase(@RequestParam Integer id, @RequestParam Integer userglod1){
        List<User> userList = (List<User>) redisTemplate.boundValueOps("user"+id).get();
        System.out.println("获取="+userList);
        if (userList == null || userList.isEmpty()) {
            return Rmed.error("用户信息未找到");
        }

        User byId = userService.findById(id);
        if (userglod1>byId.getUserglod1()){
            return Rmed.error("您的金币不足");
        }else {
            int a=byId.getUserglod1()-userglod1;
            byId.setUserglod1(a);
            userService.update(a,id);

            userList.get(0).setUserglod1(a); // 更新用户对象
            redisTemplate.boundValueOps("user"+id).set(userList);
            System.out.println("更新="+userList.get(0));

            return Rmed.suceess();
        }
    }

    @RequestMapping("/addPurchase")
    public Rmed addPurchase(@RequestParam Integer id,@RequestParam Integer pid,@RequestParam Integer amount,@RequestParam Integer chapterId,@RequestParam String pname,@RequestParam String title){
        try {
            Recharge purchase = new Recharge();
            purchase.setPid(pid);
            purchase.setPname(pname);
            purchase.setChapterId(chapterId);
            purchase.setAmount(amount);
            purchase.setUid(id);
            purchase.setPay(1);
            purchase.setPaytime(new Date());
            purchase.setMaketime(new Date());
            purchase.setContent("购买"+pname+"的"+title+"章节");
            purchase.setTypename("2");
            userService.addPurchase(purchase);
            return Rmed.suceess();
        } catch (Exception e) {
            e.printStackTrace();
            return Rmed.error("系统错误，请稍后再试");
        }

    }

    @RequestMapping("/findPurchase")
    public Rmed findPurchase(@RequestParam Integer uid,@RequestParam Integer pid,@RequestParam Integer chapterId){
        List<Recharge> purchases = userService.findPurchase(uid, pid, chapterId);
        if (purchases.size() == 0){
            return Rmed.error("没有找到该记录");
        }else {
            return Rmed.suceess();
        }
    }

    @RequestMapping("/findOne/{id}")
    public User findOne(@PathVariable("id") Integer id){
        return userService.findOneUser(id);
    }

    @RequestMapping("/exchangeGlod")
    public void exchangeGlod(@RequestBody ExchangeVo exchangeVo){
        userService.exchangeGlod(exchangeVo);
    }

    @RequestMapping("/updateVip")
    public void updateVip(Integer id){
        userService.updateVip(id);
    }

}
